package com.hkzhao.shixun.controller;
import cn.hutool.core.lang.Pair;
import com.hkzhao.shixun.common.api.CommonPage;
import com.hkzhao.shixun.common.api.CommonResult;
import com.hkzhao.shixun.common.utils.TokenUtil;
import com.hkzhao.shixun.dto.*;
import com.hkzhao.shixun.mbg.mapper.ActivityMapper;
import com.hkzhao.shixun.mbg.model.*;
import com.hkzhao.shixun.service.AdminService;
import com.hkzhao.shixun.service.StatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
@RestController
@Api(tags = "admin",description = "admin接口列表")
@RequestMapping("/admin")
public class AdminController
{
    @Autowired
    private AdminService adminService;
    @Autowired
    private StatService statService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired(required=false)
    private ActivityMapper activityMapper;
    @ApiOperation("添加管理员")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public CommonResult register(@RequestBody AdminDto adminDto){
        return adminService.register(adminDto.getUsername()+"_adm",adminDto.getPassword());
    }
    @ApiOperation("管理员登陆")
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public CommonResult login(@RequestBody CoreLoginParam coreLoginParam, BindingResult bindingResult){
        String token = adminService.login(coreLoginParam.getUsername()+"_adm",coreLoginParam.getPassword());
        if(token==null){
            return CommonResult.validateFailed("用户密码名错误");
        }
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return CommonResult.success(tokenMap);
    }
    @ApiOperation("获取活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getactivity",method=RequestMethod.GET)
    public CommonResult getactivity(@RequestParam(required=false) String activityid,@RequestParam(required=false) String tag,@RequestParam(required=false) String title,
                                    @RequestParam(required=false) String status,@RequestParam @ApiParam("页码") int pageNum, @RequestParam @ApiParam("页面的大小") int pageSize)
    {
        List<Activity> res=adminService.getActivityby(activityid,tag,title,status,pageNum,pageSize);
        if (res.size()==0) return CommonResult.failed("没有记录");
        return CommonResult.success(CommonPage.restPage(res));
    }
    @ApiOperation("添加活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/newactivity",method=RequestMethod.POST)
    public CommonResult newact(@RequestBody ActivityDto act, HttpServletRequest httpServletRequest)
    {
        String uname=adminService.getAdminbytoken(httpServletRequest);
        String actid=UUID.randomUUID().toString();
        statService.create(actid);
        Pair<String,String> url=adminService.newActivity(actid,act.getTag(),act.getTitle(),act.getStartDate(),act.getEndDate(),act.getCostintegral(),act.getDescription(),uname,act.getParticipate(),act.getDrawstype(),act.getDrawsnum(),act.getStatus());
        List<PrizeDto> lp=act.getPrizes();
        for (PrizeDto x:lp)
        {
            adminService.addPrize(UUID.randomUUID().toString(),actid,x.getLevel(),x.getOdd(),x.getDescription(),x.getNums(),x.getUrl());
        }
        Map<String,Object> mp=new HashMap<>();mp.put("url",url.getKey());
        mp.put("qrcode",url.getValue());
        return CommonResult.success(mp);
    }
    @Deprecated
    @ApiOperation("添加奖品")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/addprize",method=RequestMethod.POST)
    public CommonResult addprize(@RequestParam String activityid,@RequestParam String level,@RequestParam Double odd,@RequestParam String description,
                                 @RequestParam Integer nums,@RequestParam MultipartFile picture) throws IOException
    {
        InputStream fis=picture.getInputStream();
        String url=adminService.pic2qiniu(fis,UUID.randomUUID().toString().replace("-",""));
        Map<String,Object> resmp=new HashMap<>();
        resmp.put("prizeid",adminService.addPrize(UUID.randomUUID().toString(),activityid,level,odd,description,nums,url));
        resmp.put("picurl",url);
        return CommonResult.success(resmp);
    }
    @ApiOperation("上传图片去七牛")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/pictoqiniu",method=RequestMethod.POST)
    public CommonResult pic2qiniu(@RequestParam MultipartFile file) throws IOException
    {
        InputStream fis=file.getInputStream();
        String url=adminService.pic2qiniu(fis,UUID.randomUUID().toString().replace("-",""));
        return CommonResult.success(url);
    }
    @ApiOperation("根据url获取二维码")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getqrbyurl",method=RequestMethod.POST)
    public CommonResult getqr(@RequestParam String url)
    {
        String qrc=adminService.genqrbase64(url);
        return CommonResult.success(qrc);
    }
    @ApiOperation("获取所有记录")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getrecord",method=RequestMethod.GET)
    public CommonResult getrecord(@RequestParam(required=false) String username,@RequestParam(required=false) String activityid,@RequestParam(required=false) String recordid,
                                  @RequestParam @ApiParam("页码") int pageNum, @RequestParam @ApiParam("页面的大小") int pageSize)
    {
        List<Lotteryrecord> res=adminService.getRecordby(username,activityid,recordid,pageNum,pageSize);
        if (res.size()==0) return CommonResult.failed("没有记录");
        return CommonResult.success(CommonPage.restPage(res));
    }
    @ApiOperation("获取奖品(根据活动id)")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getprize",method=RequestMethod.GET)
    public CommonResult getprize(@RequestParam(required=false) String activityid)
    {
        List<Prize> res=adminService.getPrizeby(activityid);
        if (res.size()==0) return CommonResult.failed("没有记录");
        return CommonResult.success(CommonPage.restPage(res));
    }
    @ApiOperation("发布活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/actactivity",method=RequestMethod.GET)
    public CommonResult actactivity(@RequestParam String activityid)
    {
        String res=adminService.actActivity(activityid);
        if (res.charAt(0)=='W') return CommonResult.failed(res);
        return CommonResult.success(res);
    }
    @ApiOperation("结束活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/endactivity",method=RequestMethod.GET)
    public CommonResult endactivity(@RequestParam String activityid)
    {
        String res=adminService.endActivity(activityid);
        if (res.charAt(0)=='W') return CommonResult.failed(res);
        return CommonResult.success(res);
    }
    @ApiOperation("删除活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/delactivity",method=RequestMethod.GET)
    public CommonResult delactivity(@RequestParam String activityid)
    {
        Boolean res=adminService.delActivity(activityid);
        if (res==false) return CommonResult.failed("找不到活动");
        statService.remove(activityid);
        return CommonResult.success(res,"ok");
    }
    @ApiOperation("编辑活动")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/modifyactivity",method=RequestMethod.GET)
    public CommonResult modifyactivity(@RequestParam String activityid,@RequestParam(required=false) String title,
                                       @RequestParam(required=false) Double costintegral,@RequestParam(required=false) Integer drawsnum)
    {
        String res=adminService.modifyActivity(activityid,title,costintegral,drawsnum);
        if (res.charAt(0)=='W') return CommonResult.failed(res);
        return CommonResult.success(res);
    }
    @ApiOperation("获取活动统计信息(不指定日期和指定活动的时候支持查询当天)")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getstat",method=RequestMethod.GET)
    public CommonResult getstat(@RequestParam(required=false) String activityid, @RequestParam(required=false) Date date)
    {
        List<StatDto> res=statService.getstat(activityid,date);
        if (date==null && activityid!=null && false)
        {
            StatDto tmp=new StatDto();
            tmp.setActivityid(activityid);tmp.setDate(TokenUtil.formatSync8(new Date(),"yyyy-MM-dd"));tmp.setVis(statService.getnow(activityid));
            res.add(tmp);
        }
        if (res==null) return CommonResult.failed("no result");
        return CommonResult.success(res);
    }
    @ApiOperation("获取当前某个activity的统计")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/getcurstat",method=RequestMethod.GET)
    public CommonResult getcurstat(@RequestParam String activityid)
    {
        StatDto tmp=new StatDto();
        tmp.setActivityid(activityid);tmp.setDate(TokenUtil.formatSync8(new Date(),"yyyy-MM-dd"));tmp.setVis(statService.getnow(activityid));
        return CommonResult.success(tmp);
    }
    @ApiOperation("假装访问")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/fakevis",method=RequestMethod.GET)
    public CommonResult fakevis(@RequestParam String activityid)
    {
        return CommonResult.success(statService.plus(activityid));
    }
    @ApiOperation("强制统计")
    @PreAuthorize("hasAuthority('admin:write_and_read')")
    @RequestMapping(value="/forcelog",method=RequestMethod.GET)
    public CommonResult forcelog()
    {
        Date t=new Date();
        ActivityExample activityExample=new ActivityExample();
        ActivityExample.Criteria r1=activityExample.createCriteria();r1.andActivityidIsNotNull();
        List<Activity> la=activityMapper.selectByExample(activityExample);
        for (Activity x:la)
            statService.transfertomysql(x.getActivityid());
        return CommonResult.success("ok");
    }
}
